package pc

import (

	// "sword"

	"fmt"
	"os"
	"strings"
	"tcsc/models"
	"tcsc/sword"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/orm"
	_ "github.com/robfig/cron"
)

var P_e = `解析form失败:`
var U_e = `更新失败:`
var I_e = `插入失败:`
var Tparse = `2006-01-02 15:04:05`
var Bm, _ = cache.NewCache("memory", `{"interval":600}`)

func FootCache(shopid string) {
	gid := "0"
	if shopid != "" {
		gid = shopid
	}
	column := models.Query(`select id,name from mt_column where type='d' and status=1 and gid=? order by sort desc limit 5`, gid)
	for _, v := range column {
		v["art"] = models.Query(`select id,name from mt_page where status=1 and cid=` + v["id"].(string) + ` order by sort desc`)
	}
	Bm.Put("foot"+shopid, column, 600*time.Second)
}
func AreaGet() {
	area := models.Query(`select * from mt_area where pid=0`)
	for _, v := range area {
		city := models.Query(`select * from mt_area where pid=` + v["id"].(string))
		for _, s := range city {
			s["area"] = models.Query(`select * from mt_area where pid=` + s["id"].(string))
		}
		v["city"] = city
	}
	Bm.Put("area", area, 600*time.Second)
}
func CityShop(shopid string) {
	var info = make(map[string]interface{})
	var slice []interface{}
	var slice2 []interface{}
	var item = make(map[string]interface{})
	item["id"] = ""
	item["area"] = "统采总部"
	if shopid == "" {
		slice = append(slice, item)
	}
	shop := models.Query(`select a.id,a.city from mt_shop a where a.status=1 and a.censoring=1 and a.style=1 order by a.recommend desc,a.sort desc,a.addtime desc`)
	if shop != nil {
		beego.Debug(shop)
		for i, v := range shop {
			beego.Debug(v["city"])
			if v["city"] != nil {
				area := models.Query(`select name from mt_area where code=` + v["city"].(string))[0]["name"]
				beego.Debug(area)
				if area != nil {
					v["area"] = area.(string) + "服务中心"
				}
				if v["id"].(string) == shopid {
					slice = append(slice, shop[i])
					slice = append(slice, item)
				} else {
					slice2 = append(slice2, shop[i])
				}
			} else {
				shop[i] = nil
			}
		}
		slice = append(slice, slice2...)
		info["currentcity"] = slice[0]
		info["citylist"] = slice[1:]
	}
	Bm.Put("cityshop"+shopid, info, 600*time.Second)
}

type BaseController struct {
	beego.Controller
	Uid       string
	ShopId    string
	ShopIdAll string //逗号分隔服务中心的所有id
}

func (c *BaseController) Prepare() {

	ip := c.Ctx.Input.IP()
	if strings.Index(ip, "183.69.137") != -1 {
		c.StopRun()
	}
	//runFlag := cron.PutIp(ip)
	//beego.Debug(ip)
	//beego.Debug(runFlag)
	//if !runFlag {
	//	c.StopRun()
	//}
	// user_agent := c.Ctx.Request.Header.Get("User-Agent")
	// iswx := strings.Index(user_agent, "MicroMessenger")
	// beego.Debug(user_agent)
	// beego.Debug(iswx)
	// beego.Debug(c.Ctx.Request.Header.Get("Accept"))
	// c.SetSession("pc", "108")
	sess := c.GetSession("pc")
	if c.GetSession("shopId") == nil {
	} else {
		// c.ShopId = ""
		c.ShopId = c.GetSession("shopId").(string)
	}
	city := c.GetSession("city")
	c.Data["currentcity"] = city
	if c.ShopIdAll == "" {
		var idArr []string
		shopid := models.Query(`select id from mt_shop where style=1`)
		for _, v := range shopid {
			idArr = append(idArr, v["id"].(string))
		}
		c.ShopIdAll = strings.Join(idArr, ",")
	}
	//sess = "2961"
	if sess != nil {
		// if vipGid := models.Query(`select a.gid from mt_member_vip a left join mt_member_vip_order b on b.uid=? where and a.id=b.vid`, sess); vipGid != nil {
		// 	if vipGid[0]["gid"].(string) != "0" {
		// 		c.ShopId = vipGid[0]["gid"].(string)
		// 	}
		// }
		c.Uid = sess.(string)
		c.Data["mem"] = models.Query(`select a.monicker,b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + c.Uid)[0]
	}
	if prohibit := models.Query(`select id from mt_member where prohibit=1 and id=?`, c.Uid); prohibit != nil {
		c.Data["json"] = ""
		c.ServeJSON()
		return
	}
	uri := c.Ctx.Request.RequestURI
	uris := strings.Split(uri, "/")
	if len(uris) >= 2 {
		uri2 := uris[1]
		if uri2 == "my" || uri2 == "del" || uri2 == "shopcar" {
			if c.Uid == "" {
				if c.IsAjax() {
					c.Data["json"] = 962 //未登入
					defer c.ServeJSON()
					return
				} else {
					c.Ctx.Redirect(302, "/login")
				}
			}
		}
		if uri2 == "my" {
			if carnum := models.Query(`select count(a.id) as num from mt_order_car a where (a.type=0 or a.type=2) and a.status=1 and a.uid=` + c.Uid); carnum != nil {
				c.Data["carnum"] = carnum[0]["num"]
			}
			if isshop := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=0 and uid=` + c.Uid); isshop != nil {
				c.Data["complate"] = 1
			}
		}
	}
	c.Data["system"] = models.System
	if c.ShopId != "" {
		c.Data["shopInformation"] = models.Query(`select qq,customservice,complaints,address,name,mail,icp,workingTime from mt_shop where id=?`, c.ShopId)[0]
	}
	if Bm.IsExist("foot" + c.ShopId) {
		c.Data["basefoot"] = Bm.Get("foot" + c.ShopId)
	} else {
		FootCache(c.ShopId)
		c.Data["basefoot"] = Bm.Get("foot" + c.ShopId)
	}
	if Bm.IsExist("cityshop" + c.ShopId) {
		c.Data["cityshop"] = Bm.Get("cityshop" + c.ShopId)
	} else {
		CityShop(c.ShopId)
		c.Data["cityshop"] = Bm.Get("cityshop" + c.ShopId)
	}
	urinav := strings.Split(uri, "?")[0]

	nav := models.Query(`select * from mt_nav_pc_my where pid=0 order by sort desc`)
	for _, v := range nav {
		son := models.Query(`select * from mt_nav_pc_my where pid=` + v["id"].(string) + ` order by sort desc`)
		for _, s := range son {
			son2 := models.Query(`select * from mt_nav_pc_my where pid=` + s["id"].(string) + ` order by sort desc`)
			for _, s2 := range son2 {
				if urinav == fmt.Sprint(s2["url"]) {
					v["is"] = 1
					s2["is"] = 1
					c.Data["title"] = s2["name"]
				}
			}
			s["son"] = son2
		}
		v["son"] = son
	}
	c.Data["nav"] = nav
}

type Del struct {
	BaseController
}

func (c *Del) Get() {
	defer c.ServeJSON()
	table := c.GetString("table")
	id := c.GetString("id")
	if istrue := models.Query(`select id from ` + table + ` where id=` + id + ` and uid=` + c.Uid); istrue != nil {
		if err := models.Exec(`update ` + table + ` set status=0 where id=` + id); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
		}
	} else {
		c.Data["json"] = 0
	}
}

type ChangeShop struct {
	BaseController
}

func (c *ChangeShop) Get() {
	var json = make(map[string]interface{})
	city := c.GetString("city")
	if city != "" {
		if city == "台州市" {
			c.DelSession("shopId")
		} else {
			cityCode := models.Query(`select code from mt_area where pid<>0 and name='` + city + `'`)[0]["code"]
			shopid := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=1 and city=?`, cityCode)[0]["id"]
			c.SetSession("shopId", shopid.(string))
		}
	} else {
		if c.GetString("shopid") == "" {
			c.DelSession("shopId")
		} else {
			c.SetSession("shopId", c.GetString("shopid"))
		}
	}
	json["status"] = 1
	c.Data["json"] = json
	c.ServeJSON()
}

type Relocation struct {
	BaseController
}

func (c *Relocation) Get() {
	var json = make(map[string]interface{})
	city := c.GetString("city")
	if area := models.Query(`select code,name from mt_area where name='` + city + `'`); area != nil {
		if shop := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=1 and city=` + area[0]["code"].(string)); shop != nil {
			json["status"] = 1
			json["name"] = city
			if city == "台州市" {
				c.SetSession("shopId", "")
			} else {
				c.SetSession("shopId", shop[0]["id"].(string))
			}
			c.SetSession("city", city)
		} else {
			json["status"] = 0
			c.SetSession("city", city)
		}
	} else {
		json["status"] = 4
		json["name"] = "台州市"
	}
	c.Data["json"] = json
	c.ServeJSON()
}

func ProductSearch(sql, uid string) []orm.Params {
	info := models.Query(sql)
	nowtimes := sword.Gettimes("")
	for _, v := range info {
		v["active"] = 0
		if sales := models.Query(`select price from mt_active_sales where pid=` + v["id"].(string) + ` and status=1 and end=0 and 
			starttime<='` + nowtimes + `' and endtime>='` + nowtimes + `'`); sales != nil {
			v["price"] = sales[0]["price"]
			v["active"] = 2
		}
		if fmt.Sprint(v["isvip"]) == "1" {
			if uid != "" {
				var gid string
				g := models.Query(`select b.id,b.style 
								from mt_product a 
								left join mt_shop b on a.gid=b.id 
								where a.id=?`, v["id"].(string))[0]
				if fmt.Sprint(g["style"]) == "0" || g["id"] == nil {
					gid = "0"
				} else {
					gid = fmt.Sprint(g["id"])
				}
				mem := models.Query(`
					select b.fold 
					from mt_member_vip_order a 
					join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id 
					where a.uid=?`, gid, uid)
				if mem != nil {
					if fold := fmt.Sprint(mem[0]["fold"]); fold != "" && fold != "<nil>" {
						v["price"] = sword.Divi(sword.Mult(fmt.Sprint(v["price"]), fold), "100")
					}
				}
			}
		}
		if gbuy := models.Query(`select price from mt_active_gbuy where pid=` + v["id"].(string) + ` and status=1 and end=0 and 
			starttime<='` + nowtimes + `' and endtime>='` + nowtimes + `'`); gbuy != nil {
			v["price"] = gbuy[0]["price"]
			v["active"] = 1
		}
		// good := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + v["id"].(string) + `) b
		// 	on a.cid=b.id where a.score>=3`)[0]["num"].(string)
		// nogood := models.Query(`select count(a.id) as num from mt_product_evaluation a join (select * from mt_order_car where pid=` + v["id"].(string) + `) b
		// 	on a.cid=b.id where a.score<3`)[0]["num"].(string)
		// if nogood == "0" {
		// 	v["hp"] = "100"
		// } else {
		// 	goodi, _ := strconv.Atoi(good)
		// 	nogoodi, _ := strconv.Atoi(nogood)
		// 	v["hp"] = goodi / (goodi + nogoodi)
		// }
		// info_keyword := fmt.Sprint(v["keywords"])
		// info_keyword = strings.Trim(info_keyword, ",")
		// if info_keyword == "" || info_keyword == "<nil>" {
		// 	info_keyword = "''"
		// }
		// v["keywords"] = models.Query(`select title from mt_keywords where id in (` + info_keyword + `)  and status=1 and type=1`)

		if fmt.Sprint(v["issellnum"]) == "1" {
			sellnum := models.Query(`select sum(a.num) as num from mt_order_car a where a.status>1 and a.pid=` + v["id"].(string))[0]["num"]

			if sellnums, ok := sellnum.(string); ok {
				v["sellnum"] = sellnums
			} else {
				v["sellnum"] = "0"
			}
		}
		v["enum"] = models.Query(`select count(a.id) as num 
			from mt_product_evaluation a 
			join mt_order_car b 
			on a.cid=b.id where b.pid=` + v["id"].(string))[0]["num"]
	}
	return info
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
